import React, { useState, useEffect, useRef } from 'react';
import { Form, Input, Button, message, Modal, Space, Card, DatePicker, Checkbox } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { connect, useIntl } from 'umi';
import moment from 'moment';
import request from '@/utils/request';

const currControl = 'Tenant';
const { confirm } = Modal;
const apiURL = '/api/services/app/Tenant/';

const TenantEdit = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [datas, setDatas] = useState<any>({});
  const formRef = useRef<any>(null);
  const intl = useIntl();

  useEffect(() => {
    const { ParentData } = props;
    if (ParentData && ParentData.id) {
      getData(ParentData.id);
    }
  }, [props.ParentData]);

  const getData = (id: number) => {
    if (id) {
      request(apiURL + 'Get', {
        method: 'GET',
        params: { id },
      }).then((response) => {
        if (response.success) {
          const result = response.result;
          setDatas(result);
          if (result.endDate) result.endDate = moment(result.endDate);
          if (result.effectDate) result.effectDate = moment(result.effectDate);
          formRef.current.setFieldsValue({ model: result });
        }
      });
    }
  };

  const onFinish = async (values: any) => {
    let act = 'Create';
    if (values.model.id) {
      act = 'Update';
    }
    request(apiURL + act, {
      method: act === 'Create' ? 'POST' : 'PUT',
      data: values.model,
    }).then((response) => {
      if (response.success) {
        message.success(intl.formatMessage({ id: 'pages.save.success' }));
        props.fetchDatas();
      }
    });
  };

  const ResetForm = () => {
    const data = {
      id: 0,
    };
    setDatas(data);
    formRef.current.resetFields();
  };

  const handleDel = () => {
    request(apiURL + 'Delete', {
      method: 'DELETE',
      data: { Id: datas.id },
    }).then((response) => {
      if (response.success) {
        message.success(intl.formatMessage({ id: 'pages.delete.success' }));
        props.fetchDatas();
        formRef.current.resetFields();
      }
    });
  };

  const showConfirm = () => {
    confirm({
      title: intl.formatMessage({ id: 'pages.warning' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'pages.delete.confirm' }),
      onOk() {
        handleDel();
      },
      onCancel() {},
    });
  };

  const initAllMenu = () => {
    setLoading(true);
    request(apiURL + 'InitTenant', {
      method: 'POST',
      params: {
        tenantid: datas.id,
      },
    }).then((response) => {
      if (response.success) {
        message.success(intl.formatMessage({ id: 'pages.init.success' }));
      }
      setLoading(false);
    });
  };

  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  };

  return (
    <Form {...layout} ref={formRef} layout="horizontal" onFinish={onFinish}>
      <Card
        title={intl.formatMessage({ id: 'pages.tenant.edit' })}
        extra={[
          <Space>
            <Button type="primary" htmlType="submit" loading={loading}>
              {intl.formatMessage({ id: 'pages.ok' })}
            </Button>
            <Button onClick={ResetForm}>{intl.formatMessage({ id: 'pages.reset' })}</Button>
            <Button loading={loading} onClick={initAllMenu} danger type="primary">
              {intl.formatMessage({ id: 'pages.init' })}
            </Button>
            <Button danger onClick={showConfirm} disabled={!datas.id}>
              {intl.formatMessage({ id: 'pages.delete' })}
            </Button>
          </Space>,
        ]}
      >
        <Form.Item hidden label="id" name={['model', 'id']}>
          <Input />
        </Form.Item>
        <Form.Item
          name={['model', 'name']}
          label={intl.formatMessage({ id: 'pages.tenancyName' })}
          rules={[{ required: true }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name={['model', 'tenancyName']}
          label={intl.formatMessage({ id: 'pages.otherName' })}
          rules={[{ required: true }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name={['model', 'telphone']}
          label={intl.formatMessage({ id: 'pages.telphone' })}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name={['model', 'adminEmailAddress']}
          label={intl.formatMessage({ id: 'pages.email' })}
          hidden={datas.id != null}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name={['model', 'effectDate']}
          label={intl.formatMessage({ id: 'pages.effectDate' })}
        >
          <DatePicker />
        </Form.Item>
        <Form.Item name={['model', 'endDate']} label={intl.formatMessage({ id: 'pages.endDate' })}>
          <DatePicker />
        </Form.Item>
        <Form.Item
          name={['model', 'connectionString']}
          label={intl.formatMessage({ id: 'pages.connectionString' })}
          hidden={datas.id != null}
        >
          <Input />
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 6 }} name={['model', 'isActive']} valuePropName="checked">
          <Checkbox>{intl.formatMessage({ id: 'pages.isActive' })}</Checkbox>
        </Form.Item>
      </Card>
    </Form>
  );
};

export default connect(({ Abp, Category }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
  Category,
}))(TenantEdit);
